﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer.Configs
{
    internal class ChatGptConfig
    {
        private static Dictionary<string,string> urls = new Dictionary<string, string>();
        private static int lastUpdateTime = 0;

        public static string GetChatGptUrls(string topic, out string errorMsg)
        {
            errorMsg = null;
            if (LoadConfig(out errorMsg) == false)
            {
                return null;
            }
            if (urls.ContainsKey(topic))
            {
                return urls[topic];
            }
            errorMsg = "没有匹配的话题,已有话题包括:" + (urls.Count > 0 ? urls.Keys.ToList()[0] : "空话题");
            return null;
        }
        private static bool LoadConfig(out string errorMsg)
        {
            errorMsg = null;
            if (urls.Count == 0 || (System.Environment.TickCount - lastUpdateTime) / 1000 > 120)
            {
                urls.Clear();
                lastUpdateTime= System.Environment.TickCount;
                var fileName = GSetting.ChatGptConfigFile;
                if (File.Exists(fileName) == false)
                {
                    errorMsg = "不存在chatpgt的配置文件" + fileName;
                    return false;
                }
                var fs = File.ReadLines(fileName);
                if (fs.Count() == 0)
                {
                    errorMsg = "存在chatpgt的配置文件,但内容为空" + fileName;
                    return false;
                }
                foreach (var line in fs)
                {
                    var s = line.Trim().Split(':');
                    urls.Add(s[0].Trim(), s[1].Trim());
                }
            }
            return true;
        }
        public static string GetAllTopics(out string errorMsg)
        {
            errorMsg = null;
            if (LoadConfig(out errorMsg) == false)
            {
                return null;
            }
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var urlItem in urls)
            {
                if(stringBuilder.Length> 0)
                {
                    stringBuilder.Append(',');
                }
                stringBuilder.Append(urlItem.Key);
            }
            return stringBuilder.ToString();
        }
    }
}
